package com.example.demo.listener;

import com.example.demo.common.Func;
import com.example.demo.common.constant.RedisKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * 在 Redis Key 过期事件中，只能获取到已过期的 Key 的名称，不能获取到值
 */
@Component
@Slf4j
public class KeyExpireListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisTemplate<String, String> redis;

    // 通过构造函数注入 RedisMessageListenerContainer 给 KeyExpirationEventMessageListener
    public KeyExpireListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void doHandleMessage(Message message) {
        // 过期的 key
        String key = new String(message.getBody());
        // 消息通道
        String channel = new String(message.getChannel());

        // 判断key是否为过期文件触发操作，若是则删除相应文件
        /*if (key.contains("expire:")) {
            String[] temp = key.split(":");
            String filePath = Func.getRootPath() + "/file/" + temp[1] + "/" + temp[2] + "/" + temp[3];
            Func.deleteFile(filePath);
        }*/
        if (key.contains(RedisKey.EXPIRE)) {
            Func.deleteFile(key.replace(RedisKey.EXPIRE, ""));
        }

        log.info("key = {}, channel = {}", key, channel);
    }
}
